/*
 *  Class name: BookServiceImpl.java
 *  Version: 1.0
 *  Date: 22.6.2014
 */

package cz.morosystems.personwebmanager.businesslayer.sevices.impl;

import cz.morosystems.personwebmanager.businesslayer.sevices.BookService;
import cz.morosystems.personwebmanager.persistencelayer.daos.BookDAO;
import cz.morosystems.personwebmanager.persistencelayer.daos.UserDAO;
import cz.morosystems.personwebmanager.persistencelayer.entities.Book;
import cz.morosystems.personwebmanager.persistencelayer.entities.User;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Michal Ďuriš
 */
@Service
@Transactional
public class BookServiceImpl implements BookService {

    @Autowired
    private BookDAO bookManager;
    
    @Autowired
    private UserDAO userManager;
    
    public BookServiceImpl() {
    }

    public void setBookManager(BookDAO bookManager) {
        this.bookManager = bookManager;
    }
    
    @Override
    public void addUsersBook(Long userID, Book book) {
        
        User user = userManager.getUserByID(userID);
        
        user.getBooks().add(book);
        
        userManager.changeUser(user);
    }

    @Override
    public void deleteUsersBook(Long userID, Long bookID) {
        
        User user = userManager.getUserByID(userID);
        Book book = bookManager.getBookByID(bookID);
        
        user.getBooks().remove(book);
        
        if(Objects.equals(user.getFavoriteBook(), book)) {
            user.setFavoriteBook(null);
        }
        
        userManager.changeUser(user);
    }
    
    @Override
    public void changeBook(Book book) {
        
        bookManager.changeBook(book);
    }

    @Override
    public void deleteBook(Long bookID) {
        
        bookManager.deleteBook(bookID);
    }

    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    @Override
    public Book getBookByID(Long bookID) {
        
        return bookManager.getBookByID(bookID);
    }

}
